<template>
    <div class="baiduMap-container">
        <el-dialog
            :title="$t('location')"
            :visible="visibleGoogleMapSite"
            :close-on-click-modal="false"
            @opened="initMap"
            width="900px"
            @close="()=>{$store.commit('setVisibleGoogleMapSite',false)}">
            
            <div id="allmap" ref="map" :style="{width:mapData.width,height:mapData.height}"></div>
            <div class="search_wrap">
                <el-input v-model="search_address" @keyup.enter.native="search">
                    <el-button slot="append" icon="el-icon-search" @click="search" @keyup.enter.native="search"></el-button>
                </el-input>
            </div>
            <div class="res_address" v-show="res_address!=null">
                <span>{{res_address}}</span>
                <el-button class="pull-right" type="primary" @click="savePoint()">{{$t('save')}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script scoped>
export default {
    name:'Header',
    components:{
    },
    props:{
        mapData:{
            type:Object,
            default:()=>{
                return {
                width:'100%',
                height:'500px',
                zoom:10,
                center:{
                    lng:102,
                    lat:23
                },
                mapObj:{},//地图对象
                markers:{},//地图上所有的标记
                }
            }
        },
        address:''
    },
    data(){
        return {
            loading:true,
            search_address:'',
            res_address:'',
            point:''
        }
    },
    watch:{

    },
    computed: {
        visibleGoogleMapSite(){
            return this.$store.state.sysStore.visibleGoogleMapSite
        }
    },
    mounted(){
    },
    methods:{
        initMap(){
            // console.log(this.mapData.mapObj,'map')
            this.mapData.mapObj = new google.maps.Map(document.getElementById("allmap"), {
                zoom: this.mapData.zoom,
                center: this.mapData.center
            });
            this.mapData.mapObj.addListener("click", (event) => {
                this.deleteMarkers()
                this.addMarker(event.latLng,true);
            });
            // this.geolocation()
            if(this.mapData.markers.lng!=null){
                this.addMarker(this.mapData.markers)
                this.point=this.mapData.markers
                this.res_address=this.address
            }
        },
        addMarker(location,flag) {
            const marker = new google.maps.Marker({
                position: location,
                map: this.mapData.mapObj,
                // draggable:true
            });
            this.mapData.markers=marker;
            console.log(this.mapData.markers)
            this.point={
                lat:this.mapData.markers.position.lat(),
                lng:this.mapData.markers.position.lng()
            } 
            if(flag){
                this.getAddressByPoint2(this.point)
            }
        },
        //查询
        search(){
            if(this.search_address!=''){
                console.log('搜索')
                this.getPointByAddress2(this.search_address)
            }
        },
        //定位
        async geolocation(){
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                (position) => {
                    console.log(position,'position---------')
                    const pos = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude,
                    };
                    if(this.mapData.markers.lng==null){
                        this.mapData.mapObj.setCenter(pos);
                    }
                    console.log(pos)
                },
                () => {
                    console.log('error')
                }
                );
            }
        },
        //地理反解析
        getAddressByPoint2(point){
            //实例化Geocoder服务
            let that=this
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({ location: new google.maps.LatLng(point.lat, point.lng) }, function geoResults(results, status) {
                console.log(results)
                //这里处理结果和上面一模一样
                if (status == google.maps.GeocoderStatus.OK) {
                    // console.log('地理反解析结果：' + results[0].formatted_address);
                    // console.log('地理反解析结果：' + results[0].geometry.location);
                    console.log(results)
                    that.res_address=results[0].formatted_address
                }
                else {
                    this.$message.error('没有找到该地址')
                }
            });
        },
        //地理解析
        getPointByAddress2(address){
            let that=this
            //实例化Geocoder服务
            var geocoder = new google.maps.Geocoder();
            //1.地理解析过程
            //请求数据GeocoderRequest为address
            geocoder.geocode({ address: address }, function geoResults(results, status) {
                //这里是回掉函数(即结果处理函数)
                //状态为Ok说明有结果
                if (status == google.maps.GeocoderStatus.OK) {
                    //一般情况下会有多个结果      
                    //第一个结果为最佳匹配的结果（匹配地名最全的结果），这里只去第一个，其他的可以根据需要自己循环出来29.        //格式化过后的地址
                    console.log('地理解析结果：' + results[0].formatted_address);
                    //geometry是一个包含bounds（界限），location（纬度/经度坐标）,location_type和viewport（视图范围）
                    //获取解析后的经纬度  
                    console.log('地理解析结果：' + results[0].geometry.location);
                    that.deleteMarkers()
                    that.mapData.mapObj.setCenter(results[0].geometry.location);
                    that.addMarker(results[0].geometry.location)
                    that.res_address=results[0].formatted_address
                }else {
                    // this.$message.error("：error " + status);
                    this.$message.error('未查询到该地址');
                }
            });
        },
        setMapOnAll(map) {
            if(this.mapData.markers.visible==true){
                this.mapData.markers.setMap(map);
            }
            // for (let i = 0; i < this.mapData.markers.length; i++) {
                // this.mapData.markers.setMap(map);
            // }
        },
        clearMarkers() {
            this.setMapOnAll(null);
        },
        deleteMarkers() {
            this.clearMarkers();
            this.mapData.markers = {};
        },
        savePoint(){
            console.log(this.point,this.res_address,'point address')
            this.$store.commit('setVisibleGoogleMapSite',false)
            this.$emit('getPoint',this.point,this.res_address)
            this.search_address=''
            this.res_address=''
            this.point=''
        }

    }
}
</script>

<style lang="less">
@color_box_bg:#EFEFEF;
@color_title:#444;
@color_text:#636162;
@color_unit:#636162;
@color_light:#ff8920;
@border_bottom:1px dashed #D1D1D1;
@border_radius:3px;
@color_unit:#8a8a8a;
.baiduMap-container{
   .el-dialog__wrapper .el-dialog .el-dialog__body{
       padding: 0;
   }
   .search_wrap{
       .el-input-group {
            position: absolute;
            top: 80px;
            width: 400px;
            left: 50%;
            margin-left: -200px;
            /* opacity: 0.5; */
            background: rgba(255,255,255,.8);
            height: 40px;
            .el-input__inner{
                background: transparent;
                height: 40px;
                border-radius: 0;
            }
        }
   }
   .res_address{
        position: absolute;
        top:450px;
        left:300px;
        margin-left: -150px;
        padding: 10px;
        width: 530px;
        background: rgba(255, 255, 255, 0.8);
        border: 1px solid #ccc;
        line-height: 30px;
   }
}
</style>